<script setup>
import { ref, computed, watch } from 'vue';
import { departments as rawDepartments, users as rawUsers } from '@/stores/mockData.js';

// 定义 emit
const emit = defineEmits(['confirm-selection']);

// 弹窗显示状态
const visible = ref(false);

// 当前选中的用户 ID 列表
const selectedUsers = ref([]);

// 全选状态
const selectAll = ref(false);

// 当前选中的部门 ID
const selectedDepartment = ref(null);

// 转换部门数据
const departments = computed(() => {
  return rawDepartments.map((name, index) => ({
    id: index + 1,
    name: name
  }));
});

// 构建部门 ID 到名称的映射
const idToDeptMap = computed(() => {
  const map = {};
  departments.value.forEach(dept => {
    map[dept.id] = dept.name;
  });
  return map;
});

// 当前选中的部门名称
const selectedDepartmentName = computed(() => {
  return selectedDepartment.value ? idToDeptMap.value[selectedDepartment.value] : null;
});

// 根据部门筛选用户
const filteredUsers = computed(() => {
  if (!selectedDepartmentName.value) return [];
  return rawUsers.filter(user => user.department === selectedDepartmentName.value);
});

// 监听全选状态变化
watch(selectAll, (checked) => {
  if (checked && selectedDepartmentName.value) {
    selectedUsers.value = filteredUsers.value.map(u => u.id);
  } else {
    selectedUsers.value = [];
  }
});

// 监听用户选择变化，同步全选状态
watch(selectedUsers, (selectedIds) => {
  if (!selectedDepartmentName.value) return;
  const allUserIds = filteredUsers.value.map(u => u.id);
  selectAll.value = allUserIds.length > 0 && selectedIds.length === allUserIds.length;
}, { deep: true });

// 处理部门切换
const handleDepartmentChange = () => {
  selectedUsers.value = [];
  selectAll.value = false;
};

// 全选/取消全选
const handleSelectAllChange = (checked) => {
  if (checked) {
    selectedUsers.value = filteredUsers.value.map(u => u.id);
  } else {
    selectedUsers.value = [];
  }
};

// 打开弹窗
const openDialog = () => {
  visible.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  visible.value = false;
};

// 确认选择
const confirmSelection = () => {
  visible.value = false;
  // ✅ 正确传递 selectedUsers（用户 ID 数组）
  emit('confirm-selection', selectedUsers.value);

};

// 暴露方法给父组件
defineExpose({ openDialog });
</script>

<template>
  <el-dialog v-model="visible" title="选择接收人" width="50%">
    <!-- 部门选择 -->
    <el-select
        v-model="selectedDepartment"
        placeholder="请选择部门"
        @change="handleDepartmentChange"
        style="width: 100%; margin-bottom: 16px;"
    >
      <el-option
          v-for="dept in departments"
          :key="dept.id"
          :label="dept.name"
          :value="dept.id"
      />
    </el-select>

    <!-- 用户列表 -->
    <div class="user-list">
      <el-checkbox-group v-model="selectedUsers">
        <el-checkbox
            v-for="user in filteredUsers"
            :key="user.id"
            :label="user.id"
            :disabled="!selectedDepartment"
            style="display: block; margin-bottom: 8px;"
        >
          {{ user.name }}
        </el-checkbox>
      </el-checkbox-group>
    </div>

    <!-- 全选按钮 -->
    <el-checkbox
        v-model="selectAll"
        :disabled="!selectedDepartment"
        @change="handleSelectAllChange"
        style="margin-top: 12px;"
    >
      全选
    </el-checkbox>

    <!-- 操作按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirmSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.user-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 8px 0;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>
